package org.swirrel.installer;

import java.lang.annotation.Annotation;
import java.util.Arrays;
import org.swirrel.annotation.ColumnAdded;
import org.swirrel.annotation.ColumnMarginChanged;
import org.swirrel.annotation.ColumnMoved;
import org.swirrel.annotation.ColumnRemoved;
import javax.swing.JTable;
import org.swirrel.annotation.ColumnSelectionChanged;
import javax.swing.table.TableColumnModel;
import javax.swing.event.TableColumnModelListener;
import javax.swing.table.DefaultTableColumnModel;
import java.lang.reflect.Field;
import java.awt.Component;
import java.util.List;
import org.swirrel.listener.SwirrelTableColumnModelListener;
import org.swirrel.util.MethodCall;

/**
 * <p>Title: Swirrel</p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2009</p>
 *
 * <p>Company: </p>
 *
 * @author not attributable
 * @version 0.1
 */
public class TableColumnModelListenerInstaller extends AbstractListenerInstaller implements SwirrelListenerInstaller {

    public TableColumnModelListenerInstaller() {
        super(Arrays.<Class<? extends Annotation>>asList(ColumnAdded.class,
                ColumnMarginChanged.class, ColumnMoved.class, ColumnRemoved.class, ColumnSelectionChanged.class),
                Arrays.<Class<?>>asList(JTable.class));
    }

    public boolean isListenerAlreadySet(Object obj) {
       TableColumnModel model = ((JTable) obj).getColumnModel();
       TableColumnModelListener[] tcmls = (model instanceof DefaultTableColumnModel)
           ? ((DefaultTableColumnModel) model).getColumnModelListeners()
           : new TableColumnModelListener[]{}; //no way to get the listeners
       for(TableColumnModelListener tml : tcmls) {
         if (tml instanceof SwirrelTableColumnModelListener) {
           return true;
         }
       }
       return false;
    }

    public void registerListener(Field field, Component comp, List<MethodCall> methodCalls) throws IllegalAccessException {
        Object obj = field.get(comp);
        ((JTable)obj).getColumnModel().addColumnModelListener(
              new SwirrelTableColumnModelListener(methodCalls.get(0),
                methodCalls.get(1), methodCalls.get(2), methodCalls.get(3), methodCalls.get(4)));
    }
}
